﻿/*----------------------------------------------------------------
    // Copyright (C) 2009 江苏华招网
    // 版权所有。 
    // 作者：周传雄 
    //
    // 文件名：DistributePlanList.cs
    // 文件功能描述：发票管理
    // 创建标识：周传雄2009-05-17
    //
    // 修改标识：
    // 修改描述：
    //
    // 修改标识：
    // 修改描述：
    //
    // 审核人：
// 审核时间：
// 审核说明：
 //----------------------------------------------------------------*/
using System;
using System.Collections;
using System.Configuration;
using System.Data;

using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using HZ.DrugTrade.Model;
using HZ.DrugTrade.IBLL;
using HZ.DrugTrade.BLLFactory;
using HZ.DrugTrade.Model.Enum;
using System.Collections.Generic;
using HZ.DrugTrade.Web;
using HZ.Common;
using System.Text.RegularExpressions;


namespace HZ.DrugTrade.Web.Enterprise.InvoiceManage
{
    public partial class InvoiceAddNo : BasePage
    {

        IBLL_Purchase iPurchase = Factory.BLL_Purchase();
        IBLL_Hospital ih = Factory.BLL_Hospital();
        private static string hospitalId;
        private static decimal old_TotalAmount;
        public InvoiceAddNo()
        {
            this.ModuleNo = Module.发票管理.ToString();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                //获取开票的医疗机构
                if (Request["hospitalId"]!=null)
                {
                    hospitalId = Request.QueryString["hospitalId"].ToString();
                }
                if (Request["isID"] != null)
                {
                    Show();
                    AlterNote();
                    change.Visible = true;
                   warm.Visible = true;
                }
                else
                {
                    divAlterNote.Visible = false;
                    Show();
                    change.Visible = false;
                   warm.Visible = false;
                }
                txtTotalAmount.Enabled = false;
                txtReson.Visible = false;
                Label3.Visible = false;
               
            }
        }

        private void Show()
        {

            if (Request["isID"] == null)
            {
                btnAdd.Text = "添加";
                lblHospital.Text = ih.GetHospitalInfoByID(hospitalId).HospitalName;
                //IList<Model.Hospital> LisHospital = new List<Model.Hospital>();

                //User user = CurrentAccount.GetUser();

                //LisHospital = iPurchase.GetUnInvoiceHospitalList(user.Org.OrgID);
                //if (LisHospital.Count > 0)
                //{
                //    ddlHospital.DataValueField = "HospitalID";
                //    ddlHospital.DataTextField = "HospitalName";
                //    ddlHospital.DataSource = LisHospital;
                //    ddlHospital.DataBind();
                //}
                //else
                //{
                //    ddlHospital.Items.Add(new ListItem("没有可以开具发票的医疗机构"));
                //    ddlHospital.Enabled = false;
                //    btnAdd.Enabled = false;
                //}


            }
            else
            {
                string InvoiceSerialID = Request.QueryString["isID"].ToString();

                if (string.IsNullOrEmpty(InvoiceSerialID))
                {
                    return;
                }
                btnAdd.Text = "修改";

                //ddlHospital.Enabled = false;

                Model.Query.Invoice QryInvoice = new Model.Query.Invoice();

                QryInvoice.InvoiceSerialID = InvoiceSerialID;

                int totalCount = 0;
                IList<Model.View.Invoice> listInvoice = iPurchase.GetInvoiceByWhere(QryInvoice, 1, 1, out totalCount);
                if (listInvoice.Count > 0)
                {
                    txtInvoiceID.Text = listInvoice[0].InvoiceID;
                    dtInvoiceTime.Text = new HZ.Common.ConvertHelper(listInvoice[0].InvoiceTime).String;
                    txtTotalAmount.Text = Convert.ToString(listInvoice[0].TotalAmount);
                    old_TotalAmount = Convert.ToDecimal(listInvoice[0].TotalAmount);
                    //医疗机构名称
                    lblHospital.Text = listInvoice[0].HospitalName;
                    //ddlHospital.Items.Add(new ListItem(listInvoice[0].HospitalName));

                }
            }


        }


        /// <summary>
        ///添加，修改发票
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnAdd_Click(object sender, EventArgs e)
        {
            if (!Page.IsValid)
            {
                return;
            }


            User user = CurrentAccount.GetUser();
            Invoice invoice = new Invoice();
            int nSuccess = 0;

            ////add by hw 2010-04-19增加判断发票号不能重复功能 查询条件 id + 发票号
            //string isID = Request["isID"] == null ? "" : Request["isID"].ToString();
            //string InvoiceID = txtInvoiceID.Text.ToString();
            //DataTable dt = iPurchase.GetPurchaseNumber(isID, InvoiceID);
            //if (dt.Rows.Count > 0)
            //{
            //    HZ.Web.WebUtil.Alert("发票号已经存在,不能重复!", this);
            //    return;
            //}
            

            //修改发票号，日期
            if (Request["isID"] != null)
            {
                change.Visible = true;
                invoice.InvoiceSerialID = Request.QueryString["isID"].ToString();
                if (txtInvoiceID.Text.Trim() == "0")
                {
                    HZ.Web.WebUtil.Alert("你输入的发票号有误", this);
                }
                invoice.InvoiceID = txtInvoiceID.Text.ToString().Trim();
                invoice.InvoiceTime = new HZ.Common.ConvertHelper(dtInvoiceTime.Text.ToString()).ToDateTime;
                string pattern = @"^\d+(\.\d+)?$";
                if (Regex.IsMatch(txtTotalAmount.Text.ToString().Trim(), pattern))
                {
                    invoice.TotalAmount = Convert.ToDecimal(txtTotalAmount.Text.ToString().Trim());
                }
                else
                {
                    HZ.Web.WebUtil.Alert("请确保你输入的金额为正数", this);
                    txtTotalAmount.Text = "";
                    txtTotalAmount.Focus();
                    return;
                }
                invoice.TotalAmount_old = old_TotalAmount;
                invoice.Altertime = DateTime.Now;
                invoice.CompanyID_PS = user.Org.OrgID;
                invoice.HospitalID = lblHospital.Text.ToString().Trim();
                invoice.Note = txtReson.Text.ToString().Trim();
                if (ckUpdate.Checked && (old_TotalAmount != Convert.ToDecimal(txtTotalAmount.Text.ToString().Trim())))
                {
                    invoice.Flag = 1;

                    if (txtReson.Text.Trim() == "")
                    {
                        HZ.Web.WebUtil.Alert("修改原因不能为空!", this);
                        txtReson.Focus();
                        return;
                    }

                }
                else
                {
                    invoice.Flag = 0;
                    txtTotalAmount.Text = old_TotalAmount.ToString();
                }
                nSuccess = iPurchase.UpdateInvoice(invoice);

                if (nSuccess == 1)
                {
                    HZ.Web.WebUtil.Alert("修改成功!", this);
                    Response.Write("<script> document.location='InvocieList.aspx';</script>");
                    return;
                }
                else if (nSuccess == 3)
                {
                    HZ.Web.WebUtil.Alert("发票号重复，请重新填写!", this);
                    return;
                }
                else
                {
                    HZ.Web.WebUtil.Alert("修改失败!", this);
                    return;
                }
            }
            //添加发票
            else
            {
                invoice.InvoiceSerialID = Guid.NewGuid().ToString();
                invoice.InvoiceID = txtInvoiceID.Text.ToString().Trim();
                invoice.CompanyID_PS = user.Org.OrgID;
                /*发票表增加的冗余字段 zdc*/
                invoice.CompanyName_PS = user.UserName;//增加的冗余字段配送企业名
                invoice.HospitalName = ih.GetHospitalInfoByID(hospitalId).HospitalName;//增加的冗余字段医疗机构名
                invoice.AreaID = ih.GetHospitalInfoByID(hospitalId).AreaID;//增加的冗余 医疗机构地区ID
                invoice.AreaName = HZ.Data.DbHelperFactory.Create().ExecuteScalar("select areaname from tb_area where areaid='" + invoice.AreaID + "'").ToString();//医疗机构地区名称
                
                invoice.InvoiceTime = new HZ.Common.ConvertHelper(dtInvoiceTime.Text.ToString()).ToDateTime;
                invoice.HospitalID = hospitalId;
                invoice.TotalAmount = 0;
                nSuccess = iPurchase.AddInvoice_Distribution(invoice, null);

                if (nSuccess == 1)
                {
                    //HZ.Web.WebUtil.Alert("添加成功!", this);
                    Response.Redirect("InvoiceDistribution.aspx?InvoiceSerialID=" + invoice.InvoiceSerialID + "&hID=" + invoice.HospitalID);
                    //Response.Write("<script> window.opener.location.href=window.opener.location.href;window.close();</script>");                   
                    return;
                }
                else if (nSuccess == 2)
                {
                    HZ.Web.WebUtil.Alert("发票号重复，请重新填写!", this);
                    return;
                }
                else
                {
                    HZ.Web.WebUtil.Alert("添加失败!", this);
                    return;
                }

            }

        }

        /// <summary>
        /// 获取票据金额修改记录
        /// </summary>
            private void AlterNote()
            {
                string InvoiceSerialID = Request.QueryString["isID"].ToString();
                IList<Model.View.Invoice> LisInvoice = new List<Model.View.Invoice>();
                Model.Query.Invoice qryCondition = new Model.Query.Invoice();
                User user = CurrentAccount.GetUser();
                qryCondition.InvoiceSerialID = InvoiceSerialID;
                qryCondition.SortFields = "Altertime desc ";
                int totalCount = 0;
                IBLL_Purchase iPurchase = Factory.BLL_Purchase();
                LisInvoice = iPurchase.GetAlterNote(qryCondition, AspNetPager1.CurrentPageIndex, AspNetPager1.PageSize, out totalCount);
                AspNetPager1.RecordCount = totalCount;
                gvAlterNote.DataSource = LisInvoice;
                gvAlterNote.DataBind();
                if (totalCount == 0)
                {
                    Label1.Text = "没有此发票的修改记录";
                    gvAlterNote.Visible = false;
                }
            }

            protected void AspNetPager1_OnPageChanged(object sender, EventArgs e)
            {
                AlterNote();
            }


            protected void ckUpdate_CheckedChanged(object sender, EventArgs e)
            {
                if (ckUpdate.Checked)
                {
                    txtTotalAmount.Enabled = true;
                    txtReson.Visible = true;
                    Label3.Visible = true;
                }
                else
                {
                    txtTotalAmount.Enabled = false;
                    txtReson.Visible = false;
                    Label3.Visible = false;
                }
            }
    }
}
